package com.example.forumsystem.demos.web.controller;

import com.example.forumsystem.demos.web.common.Constans;
import com.example.forumsystem.demos.web.common.ResultCode;
import com.example.forumsystem.demos.web.model.ArticleInfo;
import com.example.forumsystem.demos.web.model.BoardInfo;
import com.example.forumsystem.demos.web.model.Result;
import com.example.forumsystem.demos.web.model.UserInfo;
import com.example.forumsystem.demos.web.service.IArticleService;
import com.example.forumsystem.demos.web.service.IBoardService;
import io.micrometer.core.lang.NonNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/article")
@Slf4j
@Api("文章接口")
public class ArticleController {
    @Autowired
    private IBoardService boardService;
    @Autowired
    private IArticleService articleService;

    @ApiOperation("发布新帖")
    @RequestMapping("/create")
    public Result create (HttpServletRequest request,
                          @ApiParam("版块Id") @RequestParam("boardId") @NonNull Long boardId,
                          @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                          @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {

        // 查询当前登录的用户信息，如果用户是禁言状态就返回失败
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);
        if (user.getState() == 1) {
            return Result.fail(ResultCode.FAILED_USER_BANNED);
        }
        // 版块的校验,如果是不能展示状态就返回
        BoardInfo board = boardService.selectById(boardId.longValue());
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return Result.fail(ResultCode.FAILED_BOARD_BANNED);
        }

        ArticleInfo article = new ArticleInfo();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());

        articleService.create(article);
        return Result.success();
    }

    @ApiOperation("获取帖子列表")
    @RequestMapping("/getAllByBoardId")
    public List<ArticleInfo> getAllByBoardId (@ApiParam("版块Id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<ArticleInfo> articles = null;

        if (boardId == null) {
            articles = articleService.selectAll();
        }else {
            articles = articleService.selectAllByBoardId(boardId);
        }

        if (articles == null){
            articles = new ArrayList<>();
        }

        return articles;
    }

    //article/getDetails
    @ApiOperation("根据帖子Id获取详情")
    @RequestMapping("/getDetails")
    public ArticleInfo getDetails (HttpServletRequest request,
                                   @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        // 从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);

        // 调用Service，获取帖子详情
        ArticleInfo article = articleService.selectDetailById(id);
        if (article == null) {
            log.info("没有查到该文章，文章id为：" + id);
        }

        if (user.getId() == article.getUserId()){
            article.setOwn(true);
        }
        return article;
    }

    @ApiOperation("修改帖子")
    @RequestMapping("/modify")
    public Result modify (HttpServletRequest request,
                             @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id,
                             @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                             @ApiParam("帖子正文") @RequestParam("content") @NonNull String content) {
        // 获取当前登录的用户
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);
        // 校验用户状态，如果是禁言状态直接返回
        if (user.getState() == 1) {
            return Result.fail(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情，如果不存在直接返回
        ArticleInfo article = articleService.selectById(id);
        if (article == null) {
            return Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断用户是不是作者，不是作者直接返回
        if (user.getId() != article.getUserId()) {
            return Result.fail(ResultCode.FAILED_FORBIDDEN);
        }
        // 判断帖子的状态 - 已归档，归档状态直接返回
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return Result.fail(ResultCode.FAILED_ARTICLE_BANNED);
        }

        articleService.modify(id, title, content);
        log.info("帖子更新成功. articleId = " + id + ", userId = " + user.getId() + ".");
        return Result.success();
    }

    @ApiOperation("点赞")
    @RequestMapping("/addOneLikeCount")
    public Result thumbsUp (HttpServletRequest request,
                               @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);

        // 检查用户的状态, 如果是禁言状态直接返回
        if (user.getState() == 1) {
            return Result.fail(ResultCode.FAILED_USER_BANNED);
        }
        articleService.addOneLikeCount(id);
        return Result.success();
    }

    @ApiOperation("删除帖子")
    @RequestMapping("/deleteById")
    public Result deleteById (HttpServletRequest request,
                                 @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);
        //用户如果是禁言状态，无法执行删除操作
        if (user.getState() == 1) {
            return Result.fail();
        }

        ArticleInfo article = articleService.selectById(id);
        // 校验帖子状态，如果是删除状态或根本没有该帖子，直接返回
        if (article == null || article.getDeleteState() == 1) {
            return Result.fail();
        }
        // 校验当前登录的用户是不是作者, 不是直接返回
        if (user.getId() != article.getUserId()) {
            return Result.fail();
        }

        articleService.deleteById(id);
        return Result.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @RequestMapping("/getAllByUserId")
    public List<ArticleInfo> getAllByUserId (HttpServletRequest request ,
                                                    @ApiParam("用户Id") @RequestParam(value = "userId", required = false) Long userId) {
        // 如果未传userId说明是要获取当前登录用户的帖子列表，userId我们从Session中获取
        if (userId == null) {
            HttpSession session = request.getSession(false);
            UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);
            userId = user.getId();
        }
        return articleService.selectByUserId(userId);
    }
}
